package com.tledu.student_manager.filter;

import com.tledu.student_manager.model.User;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@WebFilter("/*")
public class LoginFilter extends HttpFilter {

    private List<String> skipUrl = Arrays.asList("/login.jsp", "/login");

    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
        if (skipUrl.contains(req.getServletPath())) {
            chain.doFilter(req, res);
            return;
        }
        // 判断是不是静态文件
        if (req.getServletPath().startsWith("/resources")) {
            chain.doFilter(req, res);
            return;
        }
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("loginUser");
        if (user == null) {
            // 未登录
            res.sendRedirect(req.getContextPath() + "/login.jsp");
        } else {
            chain.doFilter(req, res);
        }

    }
}
